package com.liveinstars.gateway.application.filter.factory;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.core.style.ToStringCreator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author ting
 */
public class IpAllowPredicateFactory extends AbstractRoutePredicateFactory<IpAllowPredicateFactory.Config> {

    private static final Log log = LogFactory.getLog(IpAllowPredicateFactory.class);

    public IpAllowPredicateFactory() {
        super(IpAllowPredicateFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("allowIp");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            try {
                String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
                if (StringUtils.isEmpty(ip)) {
                    return false;
                } else {
                    ip = ip.split(",")[0];
                }
                return config.getAllowIp().contains(ip);
            } catch (Exception e) {
                return false;
            }
        };
    }

    @Validated
    public static class Config {
        private String allowIp;

        public String getAllowIp() {
            return allowIp;
        }

        public IpAllowPredicateFactory.Config setAllowIp(String allowIp) {
            this.allowIp = allowIp;
            return this;
        }

        @Override
        public String toString() {
            return new ToStringCreator(this)
                    .append("allowIp", allowIp)
                    .toString();
        }
    }
}
